<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>超市订单管理系统</title>
    <link type="text/css" rel="stylesheet" href="../css/style.css"/>
    <link type="text/css" rel="stylesheet" href="../css/public.css"/>
    <link rel="stylesheet" href="../element-ui/index.css"/>
    <style>
        body {
            background-color: white;
        }

        .avatar-uploader .el-upload {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }

        .avatar-uploader .el-upload:hover {
            border-color: #409EFF;
        }

        .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 50px;
            height: 50px;
            line-height: 50px;
            text-align: center;
        }

        .avatar {
            width: 50px;
            height: 50px;
            display: block;
        }
    </style>
</head>
<body>
<div class="location">
    <strong>你现在所在的位置是:</strong>
    <span>订单管理页面 &gt;&gt; 订单修改页面</span>
</div>
<div id="billUpdate">
    <el-form :model="bill" :rules="rules" ref="bill" label-width="90px"
             style="margin-top:50px;margin-left: 20%; width: 1000px" size="medium ">
        <el-form-item label="订单封面:">
            <el-upload
                    ref="fileUpload"
                    class="avatar-uploader"
                    action="#"
                    :show-file-list="false"
                    :on-change="addFile"
                    :auto-upload="false">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <img v-else src="../images/default.png" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
        </el-form-item>
        <el-form-item label="订单编码:" prop="billCode">
            <el-col :span="8">
                <el-input v-model="bill.billCode"></el-input>
            </el-col>
        </el-form-item>
        <el-form-item label="商品名称:" prop="productName">
            <el-col :span="8">
                <el-input v-model="bill.productName"></el-input>
            </el-col>
        </el-form-item>
        <el-form-item label="商品单位" prop="productUnit">
            <el-col :span="8">
                <el-input v-model="bill.productUnit"></el-input>
            </el-col>
        </el-form-item>
        <el-form-item label="商品数量" prop="productCount">
            <el-col :span="8">
                <el-input v-model="bill.productCount"></el-input>
            </el-col>
        </el-form-item>
        <el-form-item label="总金额" prop="totalPrice">
            <el-col :span="8">
                <el-input v-model="bill.totalPrice"></el-input>
            </el-col>
        </el-form-item>
        <el-form-item label="供应商" prop="providerId">
            <el-col :span="8">
                <el-select v-model="bill.providerId" placeholder="请选择供应商" style="width: 100%;">
                    <el-option
                            v-for="provider in providerList"
                            :key="provider.id"
                            v-bind:label="provider.proName"
                            v-bind:value="provider.id"
                    ></el-option>
                </el-select>
            </el-col>
        </el-form-item>
        <el-form-item label="是否付款" prop="isPayment">
            <el-radio-group v-model="bill.isPayment">
                <el-radio :label="1">未付款</el-radio>
                <el-radio :label="2">已付款</el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="updBill">保存</el-button>
            <el-button @click="cancel">取消</el-button>
        </el-form-item>
    </el-form>
</div>
<script src="../js/vue.js"></script>
<script src="../js/axios.min.js"></script>
<script src="../element-ui/index.js"></script>
<script>
    var billCode; //数据回显时的billCode
    //自定义校验规则
    var checkBillCodeUpd = (rule, value, callback) => {
        if (value != null) {
            //value就是对应el-form-item绑定的值，所以别忘了加上key（billCode）。
            //一定要保证每个分支都有callBack（），不然返回不了。
            axios.get("../bill/checkByBillCodeUpd", {params: {'billCode': value, 'self': billCode}})
                .then(response => {
                    if (response.data.flag) {
                        return callback();
                    } else {
                        callback(new Error("该编码已被占用"));
                    }
                })
                .catch(error => {
                    console.log(error)
                });
        } else {
            callback();
        }
    };

    var vue = new Vue({
        el: "#billUpdate",
        data: {
            bill: {
                billCode: "",
                productName: "",
                productUnit: "",
                productCount: "",
                totalPrice: "",
                providerId: "",
                isPayment: 1,  //是否付款，默认选中1，即未付款
                img: "",
            },
            imageUrl: "",
            providerList: [], //供应商列表
            rules: {
                billCode: [
                    {required: true, message: '请输入订单编码', trigger: 'blur'},
                    {validator: checkBillCodeUpd, trigger: 'blur'}
                ],
                productName: [
                    {required: true, message: '请输入商品名称', trigger: 'blur'},
                ],
                productCount: [
                    {required: true, message: '请输入商品数量', trigger: 'blur'},
                ],
                productUnit: [
                    {required: true, message: '请输入商品单位', trigger: 'blur'},
                ],
                totalPrice: [
                    {required: true, message: '请输入总金额', trigger: 'blur'},
                ],
                providerId: [
                    {required: true, message: '请选择供应商', trigger: "change"},
                ],
            },
        },
        created() {
            this.loadData_providers();
            this.loadData_bill();
        },
        methods: {
            //加载供应商下拉列表
            loadData_providers() {
                var url = "../provider/findAll";
                axios.get(url)
                    .then(response => {
                        this.providerList = response.data.data;
                    })
                    .catch(error => {
                        console.log(error);
                    })
            },

            //数据回显
            loadData_bill() {
                var url = "../bill/findById?id=" + sessionStorage.id;
                axios.get(url)
                    .then(response => {
                        this.bill = response.data.data
                        billCode = this.bill.billCode;
                    })
                    .catch(error => {
                        console.log(error);
                    })
            },

            //当选取文件变化时，把新的文件显示，但并未提交服务器保存
            addFile(file) {
                this.imageUrl = URL.createObjectURL(file.raw);
                this.file = file;
            },

            //修改完提交
            async updBill() {
                //验证表单，若不正确则不提交
                this.$refs['bill'].validate((valid) => {
                    if (valid) {
                    } else {
                        return false;
                    }
                });

                //先把文件上传
                await this.$refs.fileUpload.submit();

                //如果文件不为空(不为空代表修改过。原本有封面不会触发，因为file是在addFile中获取)就保存
                if (this.file != null && this.file != "") {
                    var formData = new FormData();
                    //添加数据， key-value
                    formData.append("file", this.file.raw);
                    //先上传文件，保存到服务器，返回bill.img的内容--保存的文件名
                    await axios.post("../bill/fileUpload", formData, {
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        }
                    })
                        .then(response => {
                            this.bill.img = response.data.data;
                            //嵌套在这里是为了确保，bill.img的值不为空。因为是axios是异步的。也可以使用async和await实现同步
                        })
                        .catch(error => {
                            this.$message.error(error.msg);
                        })
                }

                //再把订单信息保存到服务器
                await axios.get("../bill/updBill", {params: this.bill})
                    .then(response => {
                        this.$message({
                            message: response.data.msg,
                            type: 'success',
                            onClose: () => {
                                location.href = "bill_list.html";
                            }
                        });
                    })
                    .catch(error => {
                        console.log(error);
                    })
            },
            //取消操作
            cancel() {
                history.back();
            },
        }
    })
</script>
</body>
</html>
